import { createSlice } from '@reduxjs/toolkit'
import request from '../../utils/request'
import {
  getTokenInfo,
  removeTokenInfo,
  setTokenInfo,
} from '../../utils/storage'

const counter = createSlice({
  name: 'counter',
  initialState: {
    login: getTokenInfo(),
  },
  reducers: {
    saveToken: (state, action) => {
      state.login = action.payload
    },
    delToken: (state, action) => {
      state.login = {}
    },
  },
})

export const { saveToken, delToken } = counter.actions

//发送验证码
export const sendCodeAsync = (mobile) => {
  return async (dispatch) => {
    const res = await request.get(`/sms/codes/${mobile}`)
    dispatch(saveToken(res.data))
  }
}

//登录请求
export const loginAsync = (data) => {
  return async (dispatch) => {
    const res = await request({
      method: 'post',
      url: '/authorizations',
      data,
    })
    // 保存token到redux
    dispatch(saveToken(res.data))
    //把token保存到本地
    setTokenInfo(res.data)
  }
}
//logout 删除redux和localstorage的token
export const Logout = () => {
  return (dispatch) => {
    //移除本地token
    removeTokenInfo()
    //移除redux的token
    dispatch(delToken())
  }
}

export default counter.reducer
